package com.example.demo.component;

import com.example.demo.config.AppValue;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 定义拦截规则：
     * 拦截未登录用户，强制退回到登录页面
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute(AppValue.SESSION_KEY) != null) {
            //用户已登录：放行通过
            return true;
        }
        //未登录：跳转到登录页面
        response.sendRedirect("/login.html");
        return false;
    }
}
